<?php
	/**
	 * SimpleDBAuthAdapter
	 * @author David Ivins
	 */
	class SimpleDBAuthAdapter implements Zend_Auth_Adapter_Interface
	{
		private $_sdb;
		private $_config;
		private $_logger;
		private $_username;
		private $_password;

		/**
		 * __construct
		 */
		public function __construct($username, $password)
		{
			$this->_sdb = Zend_Registry::get('sdb'); 
			$this->_config = Zend_Registry::get('config');
			$this->_logger = Zend_Registry::get('logger'); 
			$this->_username = $username;
			$this->_password = sha1($password);
			$this->_unencrypted_password = $password;
		}
		
		/**
		 * authenticate
		 * @throws Amazon_SimpleDB_Exception
		 */
		public function authenticate()
		{
			$code = Zend_Auth_Result::FAILURE;
			$identity = $this->_username;
			$msgs = array("username and password did not match.");

			$domain = $this->_config->domain->name->users;
			$query_str = "['username' = '{$this->_username}']";

			$user_query_response = $this->_sdb->query($domain, $query_str);

			if ($user_query_response->isSetQueryResult()) 
			{ 
				$item_name_list = $user_query_response->getQueryResult()->getItemName();
				$username = $item_name_list[0];
				
				if (isset($username))
				{
					$attributes = array("password");
					$password_attribute_response = $this->_sdb->getAttributes($domain, $username, $attributes);

					if ($password_attribute_response->isSetGetAttributesResult()) 
					{ 
						$attribute_list = $password_attribute_response->getGetAttributesResult()->getAttribute();
						$attribute = $attribute_list[0];
						
						if ($attribute->isSetValue())
						{
							$password = $attribute->getValue();

							if ($this->_password == $password)
							{
								$code = Zend_Auth_Result::SUCCESS;
								$msgs[] = "Success";
							}
						}
					}
				}
			} 

			$result = new Zend_Auth_Result($code, $identity, $msgs);

			if ($result->getCode() != Zend_Auth_Result::SUCCESS)
			{
				$msg = "Failed login attempt from user {$this->_username} "
					. "with password {$this->_unencrypted_password}.";
				$this->_logger->log('(' . get_class($this) . ') ' . $msg, Zend_Log::NOTICE);
			}

			return $result;
		}
	}
